<template>
  <a-modal v-model:visible="visible" :title="title" :maskClosable="false" :footer="null">
    <a-form :label-col="labelCol">
      <a-row>
        <a-col :md="12" :xs="24">
          <a-form-item label="用户名" v-bind="validateInfos.username">
            <a-input v-model:value="formState.username" placeholder="请输入用户名" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :xs="24">
          <a-form-item label="昵称" v-bind="validateInfos.nickName">
            <a-input v-model:value="formState.nickName" placeholder="请输入昵称" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :xs="24">
          <a-form-item label="手机号" v-bind="validateInfos.phone">
            <a-input v-model:value="formState.phone" placeholder="请输入手机号" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :xs="24">
          <a-form-item label="邮箱" v-bind="validateInfos.email">
            <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :xs="24">
          <a-form-item label="部门">
            <a-tree-select
              v-model:value="formState.dept.id"
              tree-data-simple-mode
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="deptOptions"
              placeholder="请选择"
              :load-data="onLoadData"
              :field-names="replaceFields"
            />
          </a-form-item>
        </a-col>
        <a-col :md="12" :xs="24">
          <a-form-item label="岗位">
            <a-select
              v-model:value="formState.jobs"
              mode="tags"
              style="width: 100%"
              placeholder="请选择"
              option-label-prop="label"
            >
              <a-select-option
                v-for="item in jobOptions"
                :key="item.name"
                :label="item.name"
                :value="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :xs="24">
          <a-form-item label="性别">
            <a-radio-group v-model:value="formState.gender">
              <a-radio value="男">男</a-radio>
              <a-radio value="女">女</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :md="12" :xs="24">
          <a-form-item label="状态">
            <a-radio-group v-model:value="formState.enabled" :disabled="formState.id === user.id">
              <a-radio v-for="item in dictOptions" :key="item.id" :value="item.value">{{
                item.label
              }}</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="角色">
        <a-select
          v-model:value="formState.roles"
          mode="tags"
          style="width: 100%"
          placeholder="请选择"
          option-label-prop="label"
        >
          <a-select-option
            v-for="item in roleOptions"
            :key="item.name"
            :label="item.name"
            :value="item.id"
            :disabled="level !== 1 && item.level <= level"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item style="margin-bottom: 0px; margin-top: 40px; text-align: right">
        <a-button type="primary" @click.prevent="onSubmit">确认</a-button>
        <a-button style="margin-left: 10px" @click="resetFields">重置</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
  import { defineComponent, toRaw, reactive, ref, watch } from 'vue';
  import { message, Form, notification } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { addUserApi, editUserApi } from '/@/api/user';
  import { getDictDetailApi } from '/@/api/dictDetail';
  import { getAllJobApi } from '/@/api/job';
  import { getAllRolesApi, getLevelApi } from '/@/api/role';
  import { getDeptsApi, getDeptSuperiorApi } from '/@/api/dept';
  import { deptTreeNodeId, reload, buildDepts } from './index';

  const replaceFields = {
    children: 'children',
    title: 'name',
    value: 'id',
    isLeaf: 'leaf',
  };

  const formState = reactive({
    id: null,
    username: null,
    nickName: null,
    gender: '男',
    email: null,
    enabled: 'false',
    roles: [] as any,
    jobs: [] as any,
    dept: { id: null },
    phone: null,
  });
  const rulesRef = reactive({
    username: [
      {
        required: true,
        message: '请输入用户名',
      },
    ],
    nickName: [
      {
        required: true,
        message: '请输入昵称',
      },
    ],
    email: [
      {
        required: true,
        type: 'email',
        message: '请输入邮箱',
      },
    ],
    phone: [
      {
        required: true,
        message: '请输入手机号',
      },
    ],
  });
  const useForm = Form.useForm;
  const { resetFields, validate, validateInfos } = useForm(formState, rulesRef);
  const userStore = useUserStore();

  export default defineComponent({
    setup() {
      const visible = ref<boolean>(false);
      const title = ref<string>('');
      watch(visible, (newVal, _oldVal) => {
        if (!newVal) {
          resetFields();
        }
      });
      const deptOptions = ref<any>([]);
      const getDepts = async (params) => {
        const res = await getDeptsApi({ ...params, enabled: true });
        const data = res.content.map(function (obj) {
          if (obj.leaf) {
            obj.isLeaf = obj.leaf;
          }
          if (obj.hasChildren) {
            obj.children = [];
          }
          return obj;
        });
        return data;
      };

      const dictOptions = ref([]);
      const roleOptions = ref([]);
      const level = ref(3);
      const jobOptions = ref([]);
      const open = async (isAdd: boolean, record) => {
        if (isAdd) {
          title.value = '新增用户';
          deptOptions.value = await getDepts({});
        } else {
          title.value = '编辑用户';
          formState.id = record.id;
          formState.username = record.username;
          formState.nickName = record.nickName;
          formState.gender = record.gender;
          formState.email = record.email;
          formState.enabled = record.enabled;
          formState.phone = record.phone;
          formState.dept.id = record.dept.id;
          record.roles.forEach(function (role) {
            formState.roles.push(role.id);
          });
          record.jobs.forEach(function (job) {
            formState.jobs.push(job.id);
          });
          const res = await getDeptSuperiorApi([formState.dept.id]);
          const data = res?.content || [];
          buildDepts(data);
          deptOptions.value = data;
        }

        //获取级别数据
        const resLevel = await getLevelApi();
        level.value = resLevel?.level;
        //获取字典数据
        const resDict = await getDictDetailApi('user_status');
        dictOptions.value = resDict?.content;
        //获取角色数据
        const resRole = await getAllRolesApi();
        roleOptions.value = resRole || [];
        //获取岗位数据
        const resJob = await getAllJobApi();
        jobOptions.value = resJob?.content;

        formState.enabled = formState.enabled.toString();
        visible.value = true;
      };

      const onLoadData = (treeNode: any) => {
        return new Promise((resolve: (value?: unknown) => void) => {
          if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
            resolve();
            return;
          }
          setTimeout(async () => {
            const id = treeNode.dataRef.id;
            const data = deptOptions.value;
            let response = await getDepts({
              pid: id,
            });
            //获取到的子节点
            const children = response ?? [];
            const dataMap = (items: Array<any>) => {
              items.find((item) => {
                if (item.id === id) {
                  //找到当前要展开的节点
                  item.children = children;
                  return items;
                }
                if (item.children && item.children.length > 0) {
                  dataMap(item.children);
                }
              });
            };
            dataMap(data || []);
            deptOptions.value = data;
            resolve(true);
          }, 200);
        });
      };

      const onSubmit = (_e: MouseEvent) => {
        validate()
          .then(async () => {
            if (!formState.dept.id) {
              message.warning('部门不能为空');
              return;
            } else if (formState.jobs.length === 0) {
              message.warning('岗位不能为空');
              return;
            } else if (formState.roles.length === 0) {
              message.warning('角色不能为空');
              return;
            }
            const user = toRaw(formState);
            const roles: Array<{ id: number }> = [];
            user.roles.forEach(function (data) {
              const item = { id: data };
              roles.push(item);
            });
            const jobs: Array<{ id: number }> = [];
            user.jobs.forEach(function (data) {
              const item = { id: data };
              jobs.push(item);
            });
            if (!!formState.id) {
              await editUserApi({ ...user, roles, jobs });
              notification['success']({
                message: '编辑用户成功',
                duration: 3,
              });
            } else {
              await addUserApi({ ...user, roles, jobs });
              notification['success']({
                message: '新增用户成功，默认密码：123456',
                duration: 3,
              });
            }

            visible.value = false;
            deptTreeNodeId.value = -1;
            reload.value = !reload.value;
          })
          .catch((err) => {
            console.log('error', err);
          });
      };

      const user = userStore.getUser;

      return {
        user,
        open,
        visible,
        title,
        onSubmit,
        labelCol: { style: { width: '70px' } },
        wrapperCol: { span: 14 },
        validateInfos,
        resetFields,
        formState,
        jobOptions,
        roleOptions,
        deptOptions,
        onLoadData,
        replaceFields,
        dictOptions,
        level,
      };
    },
  });
</script>
